#include "mvc_model.h"
#include <QtCore>


mvc_model::mvc_model( QMap<QString,int> &datamap,QObject* parent)
    :datamap(datamap),QAbstractTableModel(parent)
{
    cols=2;
    rows=datamap.size();
    keylist=datamap.keys();
}

mvc_model::mvc_model()
{ cols=2;}

void mvc_model::init(QMap<QString,int> &datamap)
{
    this->datamap=datamap;
    rows=datamap.size();
    keylist=datamap.keys();
    reset();//重新赋值后必须重启模型
}

void mvc_model::save(QMap<QString,int> &datamap)
{
    datamap=this->datamap;
}

//-----------------------------------------------------------------
int mvc_model::rowCount(const QModelIndex & /*parent*/) const
{
    return rows;
}

//-----------------------------------------------------------------
int mvc_model::columnCount(const QModelIndex & /*parent*/) const
{
    return cols;
}

//-----------------------------------------------------------------
QVariant mvc_model::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DisplayRole ||role == Qt::EditRole)
    {
        if(index.column()==0)    return keylist[index.row()];
        else return datamap[ keylist[index.row()] ];

    }
    else if(role==Qt::TextAlignmentRole)
    {
        return Qt::AlignCenter;
    }

    else return QVariant();
}



bool mvc_model::setData(const QModelIndex & index, const QVariant & value, int role)
{
    if (role == Qt::EditRole)
    {
       if(index.column()==1)
       datamap[ keylist[index.row()]] = value.toInt();

      //  emit editCompleted( result );
    }
    return true;
}


Qt::ItemFlags mvc_model::flags(const QModelIndex & /*index*/) const
{
    return Qt::ItemIsSelectable |  Qt::ItemIsEditable | Qt::ItemIsEnabled ;
}



QDataStream &operator <<(QDataStream &out,const mvc_model &mvcm )
{
    out<<mvcm.datamap;
    return out;
}
QDataStream &operator >>(QDataStream &in, mvc_model &mvcm )
{
    in>>mvcm.datamap;
    return in;
}
